package com.lhy.wcss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhy.wcss.common.BaseConstant;
import com.lhy.wcss.common.utls.SessionUtils;
import com.lhy.wcss.model.domain.*;
import com.lhy.wcss.mapper.ApplicationMapper;
import com.lhy.wcss.model.dto.ApplicationDTO;
import com.lhy.wcss.model.dto.PageDTO;
import com.lhy.wcss.model.vo.ApplicationVO;
import com.lhy.wcss.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application> implements ApplicationService {
    @Autowired
    private StudentDataService studentDataService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private KnrdService knrdService;

    @Autowired
    private UserManageService userManageService;
    @Autowired
    private BatchSettingService batchSettingService;
    @Autowired
    private RoleFlowSettingService roleFlowSettingService;
    @Autowired
    private AuditHistoryService auditHistoryService;


    @Override
    public Page<Application> pageList(PageDTO pageDTO, Application application) {
        QueryWrapper<Application> wrapper =new QueryWrapper<>();
        Page<Application> page=new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        baseMapper.selectPage(page,null);
        return page;
    }

    @Override
    @Transactional
    public void mySaves(ApplicationDTO applicationDTO){
        this.save(applicationDTO);
    }

    @Override
    public void mySave(Application application) {
        /*当前application只有batchId和reason
         * 需要补全其他数据*/

        //补全学生sn和学生姓名
        WhitelistSetting curUser = SessionUtils.getCurUser();
        application.setName(curUser.getName()).setSn(curUser.getSn()).setApplyDate(LocalDate.now());

        /*补全学生其他信息==》studentData表*/
        QueryWrapper<StudentData> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(StudentData::getSn,curUser.getSn());
        StudentData one = studentDataService.getOne(wrapper);
        application.setCollegeName(one.getCollege())
                .setMajorName(one.getMajor())
                .setClassName(one.getClazz())
                .setClassSn(one.getClassCode())
                .setMajorSn(one.getMajorCode())
                .setCollegeSn(one.getCollegeCode())
                .setGender(dictionaryService.getByNameAndType(one.getGender(), BaseConstant.DICTIONARY_TYPE_GENDER));
        /*补全困难等级*/
        QueryWrapper<Knrd> wrapper1=new QueryWrapper<>();
        wrapper1.lambda().eq(Knrd::getStudentId,curUser.getSn()).groupBy(Knrd::getStudentId);
        Knrd knrd = knrdService.getOne(wrapper1);
        application.setDifficultyLevel(dictionaryService.getByNameAndType(knrd.getPovertyLevel(),BaseConstant.DIFFICULTY_TYPE_LEVEL))
        .setCurrentNodeCode(BaseConstant.START_NODE_CODE)
        .setStatus(BaseConstant.APPLY_STATUS_DSH);
        this.save(application);
    }

    @Override
    public Page<Application> waitAuditList(PageDTO pageDTO, Application application) {
        WhitelistSetting curUser = SessionUtils.getCurUser();
        Page<Application> page=new Page<>(pageDTO.getPageNum(),pageDTO.getPageSize());
        //获取当前用户所带的组织
        QueryWrapper<UserManage> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(UserManage::getUserSn,curUser.getSn());
        List<UserManage> list = userManageService.list(wrapper);//获取当前用户所带组织的集合
        //获取所带组织的SN
        List<String> sns = list.stream().map(u -> u.getOrganizationSN()).collect(Collectors.toList());

        QueryWrapper<Application> queryWrapper = new QueryWrapper<>();
        //辅导员
        if(BaseConstant.TEACHER_ID.equals(curUser.getRoleId())){
            queryWrapper.lambda().in(Application::getClassSn,sns)
                    .eq(Application::getStatus,BaseConstant.APPLY_STATUS_DSH)
                    .eq(Application::getCurrentNodeCode,BaseConstant.START_NODE_CODE);
        }else if (BaseConstant.COLLEGE_ID.equals(curUser.getRoleId())){//学院用户
            queryWrapper.lambda().in(Application::getCollegeSn,sns)
                    .eq(Application::getStatus,BaseConstant.APPLY_STATUS_DSH)
                    .eq(Application::getCurrentNodeCode,BaseConstant.COLLEGE_NODE_CODE);
        }else{//学校用户
            queryWrapper.lambda().eq(Application::getStatus,BaseConstant.APPLY_STATUS_DSH)
                    .eq(Application::getCurrentNodeCode,BaseConstant.SCHOOL_NODE_CODE);
        }
        this.page(page,queryWrapper);

        page.getRecords().stream().forEach(app->{
            app.setBatchSetting(batchSettingService.getById(app.getBatchId()));

            //补充性别 困难等级，当前节点
        });

        return page;

    }

    @Override
    public void audit(Application application) {
        //原申请
        Application app = this.getById(application.getId());
        WhitelistSetting curUser = SessionUtils.getCurUser();
        //根据节点code获取节点名称
        RoleFlowSetting node=roleFlowSettingService.getByCode(app.getCurrentNodeCode());

        AuditHistory history=new AuditHistory().setApplicationId(application.getId())
                .setAuditBy(curUser.getSn())
                .setAuditorName(curUser.getName())
                .setAuditComment(application.getAuditComment())
                .setStatus(application.getStatus())
                .setAuditNodeCode(app.getCurrentNodeCode())
                .setAuditNodeName(node.getNodeName());

        //先判断是否成功
        if(BaseConstant.APPLY_STATUS_BTG.equals(application.getStatus())){
            //审核历史
            auditHistoryService.save(history);
            //不成功
            this.updateById(application);
        }else{
            //成功需要判断角色
            //辅导员和学院通过进入下一节点，状态不变，学校进入下一节点状态要变
            app.setAuditComment(application.getAuditComment())
                    .setCurrentNodeCode(node.getNextNode());
            if(BaseConstant.SCHOOL_NODE_CODE.equals(curUser.getRoleId())) {
                app.setStatus(application.getStatus());
            }
            this.updateById(app);
            auditHistoryService.save(history);
        }
    }

    @Override
    public void audits(ApplicationDTO applicationDTO) {
        applicationDTO.getApps().stream().forEach(app->audit(app));
    }


}
